package com.umgsai.wx.backend.test;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;

import java.util.List;

public class Merge {

    /**
     * 合并两个有序数组
     */
    public static void main(String[] args) {
        List<Integer> list1 = Lists.newArrayList(1, 2, 3, 4, 7, 8);
        int[] nums1 = new int[list1.size()];
        for (int i = 0; i < list1.size(); i++) {
            nums1[i] = list1.get(i);
        }

        List<Integer> list2 = Lists.newArrayList(2, 5, 6);
        int[] nums2 = new int[list2.size()];
        for (int i = 0; i < list2.size(); i++) {
            nums2[i] = list2.get(i);
        }

        int[] merge = merge(nums1, nums1.length, nums2, nums2.length);
        System.out.println(JSON.toJSONString(merge));
    }

    public static int[] merge(int[] nums1, int m, int[] nums2, int n) {
        int[] result = new int[m + n];
        int i = 0;
        int j = 0;
        int resultLength = 0;

        if (nums1 == null) {
            return nums2 == null ? new int[0] : nums2;
        }
        if (nums2 == null) {
            return nums1;
        }


        while (true) {
            if (i >= m && j >= n) {
                break;
            }
            if (i >= m) {
                while (j < n) {
                    result[resultLength++] = nums2[j++];
                }
                break;
            }
            if (j >= n) {
                while (i < m) {
                    result[resultLength++] = nums1[i++];
                }
                break;
            }

            int temp = nums1[i];
            if (temp > nums2[j]) {
                temp = nums2[j];
                j++;
            } else {
                i++;
            }
            result[resultLength++] = temp;
        }
        return result;
    }
}
